package com.clstu.arrays_;

import java.util.Arrays;
import java.util.Comparator;

//利用Arrays类提供的方法对数组进行排序，类数组
public class ArraysExcercise {
    public static void main(String[] args) {
        Book[] books=new Book[4];
        books[0]=new Book("红楼梦",100);
        books[1]=new Book("金瓶梅新",90);
        books[2]=new Book("去年文摘新",5);
        books[3]=new Book("java从入门到放弃~",300);
        Arrays.sort(books, new Comparator(){//Comparator是接口
            //因为已知传入的都是Book类型的对象，所以可以向下转型
            @Override
            public int compare(Object o1, Object o2) {
                Book b1=(Book) o1;
                Book b2=(Book) o2;
                return (int)(b1.getPrice()-b2.getPrice());//价格低到高
            }
        });
        System.out.println(Arrays.toString(books));
        Arrays.sort(books, new Comparator(){
            //因为已知传入的都是Book类型的对象，所以可以向下转型
            @Override
            public int compare(Object o1, Object o2) {
                Book b1=(Book) o1;
                Book b2=(Book) o2;
                return (int)(b2.getPrice()-b1.getPrice());//价格高到低
            }
        });
        System.out.println(Arrays.toString(books));
        Arrays.sort(books, new Comparator(){
            //因为已知传入的都是Book类型的对象，所以可以向下转型
            @Override
            public int compare(Object o1, Object o2) {
                Book b1=(Book) o1;
                Book b2=(Book) o2;
                return b2.getName().length()-b1.getName().length();//名字长到短
            }
        });
        System.out.println(Arrays.toString(books));

    }
}
class Book{
    private String name;
    private double price;

    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return
                "name='" + name + '\'' +
                ", price=" + price +
                '\n';
    }
}